#include <iostream>
#include <string>
#include <mutex>
#include <thread>
// thread_local是定义在值类型中的
// 比如: data type like int, string, char, etc. 
std::mutex coutMutex;
thread_local int n = 2;
thread_local std::string str("hello Educba from thread number and address of the string is ");
void thread_integer(int n_val)
{
    n = n_val;
}

void thread_cnt()
{
    std::cout << n << std::endl;
}

void thread_func(int td)
{
    // 这里改变的只是本线程的数据，不会改变其它线程的
    thread_integer(td);
    ++n;
    thread_cnt();
}

void thread_string(std::string const &aStr)
{
    str += aStr;
    std::lock_guard<std::mutex> guard(coutMutex);
    std::cout << str << std::endl;
    std::cout << "&str: " << &str << std::endl;
    std::cout << std::endl;
}

int main_thread_local()
{
    n = 4;
    std::thread it1(thread_func, 1);
    std::thread it2(thread_func, 2);
    std::thread it3(thread_func, 3);
    it1.join();
    it2.join();
    it3.join();
    std::cout << n << std::endl;
    std::cout << std::endl;

    std::thread tt1(thread_string, "thread number 1");
    std::thread tt2(thread_string, "thread number 2");
    std::thread tt3(thread_string, "thread number 3");
    std::thread tt4(thread_string, "thread number 4");
    tt1.join();
    tt2.join();
    tt3.join();
    tt4.join();

    /*
    输出的结果是:
    2
    4
    3
    4

    hello Educba from thread number and address of the string is thread number 1
    &str: 0x7f9f60f05bc8

    hello Educba from thread number and address of the string is thread number 2
    &str: 0x7f9f61904088

    hello Educba from thread number and address of the string is thread number 3
    &str: 0x7f9f60f05a48

    hello Educba from thread number and address of the string is thread number 4
    &str: 0x7f9f61a04088
    */
}